from PIL import Image,ImageDraw,ImageFont,ImageFilter
import random
from io import BytesIO
import os
import numpy as np

# 获取随机验证码 默认长度=1
def random_code(length=1):
    # _letter_cases = "abcdefghjkmnpqrstuvwxy"  # 小写字母，去除可能干扰的i，l，o，z
    # _upper_cases = _letter_cases.upper()  # 大写字母
    _letter_cases = ""
    _upper_cases = ""
    _numbers = ''.join(map(str, range(3, 10)))  # 数字
    init_chars = ''.join((_letter_cases, _upper_cases, _numbers))

    code = ''
    for char in range(length):
        code += init_chars[random.randint(0, len(init_chars)-1)]
    return code

# 随机颜色 默认颜色范围【1，255】
def random_color(s=1,e=255):
    return (random.randint(s,e),random.randint(s,e),random.randint(s,e))

# 生成验证码图片
#length 验证码长度
#width 图片宽度
#height 图片高度
#返回验证码和图片
def veri_code(length=4,width=160,height=60,save=False):
    #创建Image对象
    image = Image.new('RGB',(width,height),(255,255,255))
    #创建Font对象
    font = ImageFont.truetype('Arial.ttf',50)
    #创建Draw对象
    draw = ImageDraw.Draw(image)
    #随机颜色填充每个像素
    for x in range(width):
        for y in range(height):
            ints = random.randint(10, 20)
            if x%ints==0:
                if y%8==0:
                    draw.point((x,y),fill=random_color(0,127))
                    draw.point((x+1,y),fill=random_color(0,127))
                    draw.point((x-1,y),fill=random_color(0,127))
                    draw.point((x,y+1),fill=random_color(0,127))
                    draw.point((x,y-1),fill=random_color(0,127))
    #验证码
    code = random_code(length)
    #随机颜色验证码写到图片上
    for t in range(length):
        draw.text((40*t+5,5),code[t],font=font,fill=random_color(0,127))
        # draw.text((40*t+5,5),code[t],font=font,fill=(0,0,0))

    #模糊滤镜
    # image = image.filter(ImageFilter.BLUR)
    # 保存
    if save :
        save_dir = "./images/"
        if os.path.exists(save_dir) == False:  # if the folder is not existed, create it
            os.mkdir(save_dir)
        image.save(save_dir + code + ".jpg", "JPEG")

    return code, image

if __name__ == "__main__":
    num = 1

    for i in range(num):
        save_dir = "./images/"
        code, image = veri_code()
        if os.path.exists(save_dir) == False:  # if the folder is not existed, create it
            os.mkdir(save_dir)
        image.save(save_dir + code + ".jpg", "JPEG")
        print(code)
        # 临时写入内存调用
        f = BytesIO()
        image.save(f, 'jpeg')
        # np.array(f.getvalue())
        # print(f.getvalue())
        captcha_image = Image.open(f)
        captcha_image = np.array(captcha_image)
        print(captcha_image)
    # print(code,image)